# coding:utf-8
from PyQt6.QtWidgets import QWidget
from qfluentwidgets import BodyLabel, setFont, VBoxLayout

from common import FakerUtils, SingleIcon
from components import BaseScrollArea, ProviderCard
from .add_order_interface import AddOrderDialog
from .faker_signal import fakerSignals


class ListOrderInterface(BaseScrollArea):
    def __init__(self, parent: QWidget = None):
        super().__init__(parent)
        self.titleLabel = BodyLabel('指令列表', self)
        self.verticalLayout = VBoxLayout(None)
        self.fakerUtils = FakerUtils()

        self.__initWidgets()
        self.init_providers()

    def __initWidgets(self):
        self.setObjectName('ListOrderInterface')
        setFont(self.titleLabel, 26)

        self.scrollLayout.setContentsMargins(36, 36, 36, 10)
        self.scrollLayout.addWidget(self.titleLabel)
        self.scrollLayout.addSpacing(20)
        self.scrollLayout.addLayout(self.verticalLayout)

        fakerSignals.addProvider.connect(self.init_providers)

    def init_providers(self):
        self.verticalLayout.removeAllWidget()
        provider: dict
        for provider in self.fakerUtils.get_providers():
            item = ProviderCard(SingleIcon.FALSE, provider['name'], self)
            item.setProperty('data', provider)
            item.removed.connect(self.remove_provider)
            item.edited.connect(self.edit_provider)  # 连接编辑信号
            self.verticalLayout.addWidget(item)

    def edit_provider(self, item: ProviderCard):
        old_data = item.property('data')
        dialog = AddOrderDialog(self.window())
        dialog.setTitle('编辑指令')
        dialog.setParams(old_data)
        if dialog.exec():
            new_data = dialog.get_data()
            self.fakerUtils.edit_provider(old_data, new_data)
            fakerSignals.editProvider.emit(new_data)

    def remove_provider(self, item: ProviderCard):
        self.verticalLayout.deleteWidget(item)
        data = item.property('data')
        self.fakerUtils.remove_provider(data)
        fakerSignals.removeProvider.emit(data)
